package Reentrantlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class Account {
        private String name; // 账户名称
        private int asset; // 账户资金
        private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); // 读写锁

        public Account(String name, int asset) { // 构造方法
            this.name = name;
            this.asset = asset; // 属性赋值
        }

        public void save(int asset) { // 写锁操作方法
            this.readWriteLock.writeLock().lock(); // 独占的写锁
            try {
                this.asset += asset; // 账户资金累加
                TimeUnit.SECONDS.sleep(1); // 模拟延迟
                System.out.println(" [" + Thread.currentThread().getName() +
                        "] 修改银行资产，当前的资产为：" + (this.asset / 100.0));
            } catch (Exception e) {
            } finally {
                this.readWriteLock.writeLock().unlock(); // 释放写锁
            }
        }

        public String toString() { // 读锁操作方法
            this.readWriteLock.readLock().lock(); // 共享读锁
            try {
                TimeUnit.MILLISECONDS.sleep(100); // 模拟延迟
                return " [" + Thread.currentThread().getName() + "] 账户名称：" + this.name +
                        ", 账户余额：" + (this.asset / 100.0);
            } catch (Exception e) {
                return null;
            } finally {
                this.readWriteLock.readLock().unlock(); // 释放读锁
            }
        }
    }

